package org.smallframework.solon;

import org.noear.solon.data.tran.TranUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sf.database.dao.DBClient;
import sf.database.util.DBUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * solon dao封装类
 * @author sxf
 */
public class SolonDaoTemplate extends DBClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(SolonDaoTemplate.class);

    public SolonDaoTemplate(DataSource dataSource) {
        super(dataSource);
    }

    public SolonDaoTemplate() {
    }

    @Override
    protected DataSource getDataSource(boolean readonly) {
        //在事务里都用master，除了readonly事务
        boolean inTrans = TranUtils.inTrans();
        if (inTrans) {
            boolean isReadOnly = TranUtils.inTransAndReadOnly();
            if (!isReadOnly) {
                return super.getDataSource(false);
            }
        }
        return super.getDataSource(readonly);
    }

    protected Connection getRealConnection(DataSource ds) {
        try {
            return TranUtils.getConnection(ds);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    protected void closeRealConnection(Connection conn, DataSource ds) {
        if (TranUtils.inTrans()) {
            return;
        }
        DBUtils.closeQuietly(conn);
    }

    @Override
    public void start() {
        // 不支持该操作
        throw new UnsupportedOperationException("no support!");
    }

    public boolean isTransaction() {
        return TranUtils.inTrans();
    }

    public boolean isCurrentTransactionReadOnly() {
        return TranUtils.inTransAndReadOnly();
    }

}
